/**
 * 首页JS代码
 *
 */

 jQuery( function(){

 	var $ = jQuery;


 	/********图片轮播组件*********/
 	/**
 	 * 
 	 *@param args  JSON  
 	 *@param args.el HTMLElement slider的外层父元素
 	 *@param args.itemClass  String  slider内的单个块，每次只能显示其中一个块
 	 *@param args.duration  Number  slider两个块切换时的动画时间，默认是 200ms 
 	 *@param args.autoRun  boolean  是否自动切换，默认为 true 
 	 *@param args.step  Number  每次动画移动的位移，默认是 el 元素的宽度
 	 *@param args.delay  Number  两次动画之间的间隔时间，默认 1000 ms 
 	 */
 	var Slider = function( args ){
 		this.$el = $(args.el);
 		this.$itemArray = $( args.itemClass, this.$el );
 		this.itemClass = args.itemClass;
 		this.currentIndex = 0;							//当前显示的块序号，从0开始
 		this.totalNumber = this.$itemArray.length;		//总的块个数
 		this.duration = args.duration;
 		this.autoRun = args.autoRun !== false;
 		this.step = args.step || this.$el.width();
 		this.delay = args.delay || 1000;
 		this.isAnimating = false;		//是否正在执行动画，动画执行过程中，不会响应用户输入
 		this.timer = null;				//动画延迟执行的timer
 		this.stoped = args.stoped === true;			//是否被停止了

 		if( this.autoRun && !this.stoped ){
			this.run();
 		}
 		//下面这个逻辑，貌似不应该属于 Slider 本身的功能
// 		this.enableAutoRun = true;		//如果用户鼠标移动到slider内，停止自动翻页
 	};

 	$.extend( Slider.prototype, {

 		doSwitch : function(){
 			clearTimeout( this.timer );
 			var newIndex = ( this.currentIndex + 1 ) % this.totalNumber;
 			var newScrollLeft = 1 * this.step;
 			this.isAnimating = true;
 			this.currentIndex = newIndex;

 			var that = this;
 			this.$el.animate( {
 				scrollLeft : newScrollLeft
 			}, {
 				duration : this.duration, 
 				complete : function(){
 					var $first = that.$el.find( that.itemClass ).eq(0); 	
 					$first.parent().append( $first );
// 					var $p = $first.parent();
// 					$first.detach().appendTo( $p );
 					that.$el.scrollLeft(0);
 					that.isAnimating = false;
 					if( typeof that.onSwitch === 'function'){
 						that.onSwitch( that.currentIndex );
 					}
 					if( that.autoRun && !that.stoped ){
 						that.run();
 					}
 				}
 			});
 		}, 

 		run : function(){
 			this.stoped = false;
 			if( !this.isAnimating ){
 				clearTimeout( this.timer );
	 			var that = this;
	 			this.timer = setTimeout( function(){
	 				that.doSwitch();
	 			}, this.delay );
 			}
 			

 			return this;
 		}, 
 		stop : function(){
 			clearTimeout( this.timer );
 			this.stoped = true;
 			
 			return this;
 		}, 
 		getCurrentIndex : function(){
 			return this.currentIndex;
 		}
 	} );






 	//首页顶部焦点区的轮播图
 	var topSlider = new Slider( {
 		el : '#pic-slider-con', 
 		itemClass : '.slider-item', 
 		autoRun : true, 
 		step : 470, 
 		duration : 500, 
 		delay : 4000
 	});


 	var $indicatorCon = $('#pic-slider-indicator-con');
 	topSlider.onSwitch = function( newIndex ){
 		var indicatorClass = 'pic-slider-indicator';
 		var indicatorActiveClass = 'pic-slider-indicator-active';
 		$indicatorCon.children( '.' + indicatorActiveClass ).removeClass( indicatorActiveClass );
 		$indicatorCon.children( '.' + indicatorClass ).eq( newIndex ).addClass( indicatorActiveClass );

 	};


 });


//处理首页请求文章列表的功能
jQuery( function(){

	var $ = jQuery;

	var _ = window._;

	var ARTICLE_TPL = '<li class="post-item clearfix">' + 
					'<img src="<%= frontcover %>" />' + 
					'<div class="post-content-wrap">' + 
						'<h4 class="post-item-title"><a class="post-item-link" target="_blank" href="/blog/index.php?r=site/showarticle&articleid=<%= id %>"><%= title %></a></h4>' + 
						'<div class="post-meta-info"><span class="post-meta-author"><%= author %></span><span class="post-meta-time"><%= update_time %></span><span class="post-meta-pv"><%= pv %></span></div>' + 
						'<div class="post-abstract"><%= summary %></div>' + 
					'</div>' + 
				'</li>';

	var articleFormat = _.template( ARTICLE_TPL );
	var $articleCon = $('#post-container');

	var CON_TOP = $articleCon.position().top;


//工具函数
	var utils = {

		getSearchConf : function(){
			var str = location.search.substring(1);
			var out ;
			if( str ){
				out = this.query2JSON( str );
			}else{
				out = {};
			}
			return out;
		}, 

		getHashConf : function(){
			var str = location.hash.replace(/^#+/, '');
			return this.query2JSON( str );
		}, 

		query2JSON : function( query ){
			var out = {};
			if( query  ){
				var arr = query.split('&');
				for( var i = 0, len = arr.length; i < len; i++ ){
					var item = arr[i];
					var itemArray = item.split('=');
					out[ itemArray[0] ] = itemArray[1] || '';
				}
			}
			return out;
		}, 

//获取当前用户选中的顶部导航类型，请求文章会用到
		getType : function( defaultValue ){
			var hashObj = this.getHashConf();
			var type = hashObj['type'] || '-1';
			try{
				type = decodeURIComponent(type);
			}catch(e){}
			return type;
		}
	};


	//负责请求文章列表的data层，单例
	var dataStore = {
		onfail : null, 
		querySign : null, 
		fail : function( res, xhr ){
			if( typeof this.onfail === 'function'){
				this.onfail();
			}
		}, 
		getData : function( start, num, callback ){
			var querySign = new Date().getTime();
			var url = this.getURL( start, num );

			this.querySign = querySign;
			var that = this;
			$.get( url ).done( function( res, xhr){
				if( that.querySign !== querySign ){
					return;
				}
				var jsonObj = JSON.parse( res );
				if( typeof callback === 'function' ){
					callback( jsonObj );
				}
			} ).fail( function( res, xhr ){
				if( that.querySign !== querySign ){
					return;
				}
				that.fail( res, xhr );
			} );
		}, 

		getURL : function( start, num ){
			var type = utils.getType();

			return '/blog/index.php?r=site/getarticle&classid=' 
				+ encodeURIComponent(type) + '&start=' + start + '&num=' + num ;
		}
	};

	//控制器
	var control = {

		state : {}, 

		init : function(){
			this.$el = $articleCon;
			this.$win = $(window);
			this.dataStore = dataStore;
			this.formatFn = articleFormat;
			this.dataStore.onfail = _.bind( this.dataError, this );
			this._setupEvent();

			//开始初始化的请求
			this.initHandle();
		}, 
		_setupEvent : function(){

			var that = this;
			var $win = this.$win;
			var timer;
			$win.scroll( function(){
				clearTimeout( timer );
				timer = setTimeout( function(){
					that.scrollHandle();
				});
			});

			$win.on( 'hashchange', function(){
				that.filterHandle();
			});

			
		}, 
		resetState : function(){

			this.state = {
				//当前显示的最后一条文章index
				endIndex : 0, 
				//每次请求的文章数目
				blockSize : 5, 
				//当前是否正在请求文章
				isRequest : false, 
				//是否已经显示完所有文章
				reachLast : false, 
				//当前相对于文章容器，竖直方向上滚动的距离
				scrollTop : 0, 
				//文章列表容器距离document顶部的距离
				containerTop : this.$el.position().top, 
				//在用户滚动到，距离最后一篇文章底部还剩这个距离时，需要请求下一个块的数据
				needRequestHeight : 200, 
				//当前用户选中的类目
				filterType : utils.getType()
			};
		}, 
		initHandle : function(){
			this.resetState();
			this.doRequest();
			navControl.render( this.state );
		}, 
		scrollHandle : function(){
			this.state.windowScrollTop = this.$win.scrollTop();
			if( this.checkScroll() ){
				this.doRequest();
			}
		}, 
		filterHandle : function(){
			this.$el.empty();
			this.resetState();
			this.doRequest();
			navControl.render( this.state );
		}, 

		//执行请求
		doRequest : function(){
			if( !this.state.isRequest && !this.state.reachLast ){
				this.state.isRequest = true;
				this.dataStore.getData( this.state.endIndex, this.state.blockSize, _.bind( this.onDataReady, this ) );
			}
			
		}, 

		//获取数据出错时，调用
		dataError : function(){
			this.state.isRequest = false;
			alert('获取文章失败，请稍后再试');
		}, 
		//文章数据成功取得的回调
		onDataReady : function( jsonObj ){
			this.state.isRequest = false;
			if( jsonObj ){
				var data = jsonObj.data;
				if( data && data.length > 0 ){
					//插入文章列表
					var html = '';
					var formatFn = this.formatFn;
					_.each( data, function( item ){
						html += formatFn( item );
					});
					this.$el.append( html );
					this.state.endIndex += data.length;
					this.state.totalHeight = this.$el.height();
				}else{
					this.state.reachLast = true;
					alert('没有更多文章了:)');
				}
			}
		}, 

		//在向下滚动过程中，检查是否需要请求新的数据
		checkScroll : function(){
			var scrollY = Math.max( 0, this.state.windowScrollTop - this.state.containerTop );
			this.state.scrollTop = scrollY;
			var containerHeight = this.state.totalHeight;
			return containerHeight - scrollY < this.state.needRequestHeight;
		}
	};

	//用户点击顶部的导航栏，需要改变当前请求文章类型
	var navControl = {

		itemClass : 'nav-item', 
		itemSelectedClass : 'nav-item-active', 

		init : function(){
			this.$el = $('#nav-list-con');
			this._setupEvent();
		}, 
		_setupEvent : function(){

			var that = this;
			this.$el.on( 'click', '.' + this.itemClass, function(e){
				var $el = $( e.target );
				if( $el.hasClass(that.itemSelectedClass) ){
					return;
				}
				var type = $el.data('type');
				if( type ){
					window.scrollTo( 0, 0 );
					location.hash = '#type=' + encodeURIComponent(type);
				}
			});
		}, 

		render : function( state ){
			var type = state.filterType;
			this.$el.find('.' + this.itemClass ).removeClass( this.itemSelectedClass );
			var $target = this.$el.find( '.' + this.itemClass + '[data-type="' + type + '"]').addClass( this.itemSelectedClass );
		}
	};

	//返回顶部按钮
	$('#back-top').click( function(){
		window.scrollTo( 0, 0 );
	});

	//浏览器滚动时，固定顶部导航栏
	var $win = $( window );
	$win.scroll( function(){
		var headerHeight = 80;
		var top = $win.scrollTop();
		if( top > headerHeight ){
			$('#head-wrap-holder').addClass('head-fixed');
		}else{
			$('#head-wrap-holder').removeClass('head-fixed');
		}
	});

	//顶部导航栏控制器
	navControl.init();

	//获取文章列表控制器
	control.init();
});